#include "mapreducewidget.h"
#include <QGridLayout>
#include <QTableWidget>
#include <QTabBar>
#include "jseditorwidget.h"
#include "HorizontalTabWidget.h"
#include "mriowidget.h"
#include <client/dbclient.h>
using namespace mongo;
#include "mainwindow.h"
MapReduceWidget::MapReduceWidget(QWidget *parent) :
    QWidget(parent)
{

    tabWidget=new QTabWidget(this);
    tabWidget->setElideMode(Qt::ElideLeft);
    tabWidget->setTabsClosable(true);
    tabWidget->setTabPosition(QTabWidget::West);
    tabWidget->setGeometry(20, 20, 300, 200);

//    //QTabBar* tabBar=new QTabBar();
//    //tabBar->setGeometry(0,0,200,50);
//    //tabWidget->setTabBar(tabBar);
    mapFuncEditor=new JsEditorWidget(this);
    reduceFuncEditor=new JsEditorWidget(this);
    finalizeFuncEditor=new JsEditorWidget(this);
//    qDebug("MrioWidget...");
    mrioWidget=new MRIOWidget(this);
    tabWidget->addTab(mapFuncEditor,tr("map function"));
    tabWidget->addTab(reduceFuncEditor,tr("reduce function"));
    tabWidget->addTab(finalizeFuncEditor,tr("finalize function"));
    tabWidget->addTab(mrioWidget,tr("input & output"));
    QGridLayout* layout=new QGridLayout();
    layout->addWidget(tabWidget);
    this->setLayout(layout);
    //QGridLayout* gridLayout=new QGridLayout();
    //gridLayout->addWidget(tabWidget);
    //setLayout(gridLayout);
    initEditor();

    connect(mrioWidget,SIGNAL(mapReduceAction()),this,SLOT(runMapReduce()));
}

void MapReduceWidget::initEditor()
{
    QString mapFunc =
            "function()\n{\n emit(this.a, 1); \n}\n";
    QString reduceFunc =
            "function(key, values)\n{\n return Array.sum(values);\n }\n";
    mapFuncEditor->setText(mapFunc);
    reduceFuncEditor->setText(reduceFunc);
}
/*
function Map()
{
    emit(this.Age,1);
}
function Reduce(key,arrj_values)
{
    var total=0;
    for(var i in arr_values)
    {
        temp=arr_values[i];
        total+=temp;
    }
    return total;
}
*/


void MapReduceWidget::runMapReduce()
{
    QString mapFunc=mapFuncEditor->text();
    QString reduceFunc=reduceFuncEditor->text();
    DBClientConnection* pConn= MainWindow::getInstance()->getSelectedConnection();
    QString ns=MainWindow::getInstance()->getSelectedCollection();
    BSONObj out;
    out=pConn->mapreduce(ns.toStdString(),mapFunc.toStdString(),reduceFunc.toStdString(),BSONObj());
    mrioWidget->setMapReduceResult(out);
}
